package com.googlecode.androidspamblocker;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsMessage;

public class SmsContactRule implements SmsRule {
	private static final String TAG = "SmsContactRule";
	
	public SmsContactRule() {
	}
	
	public int match(SmsMessage msg, Context context) {
		String address = msg.getOriginatingAddress();
		if(contactExists(address, context)) {
			return SmsAction.IN;
		}
		return SmsAction.UNKNOWN;
	}
	
	public int match(SmsMessage[] msg, Context context) {
		String address = msg[0].getOriginatingAddress();
		if(contactExists(address, context)) {
			return SmsAction.IN;
		}
		return SmsAction.UNKNOWN;
	}
	
	public void load(String rule) {
	}
	
	public String toStrig() {
		return null;
	}
	
	private boolean contactExists(String number, Context context) {
		boolean ret = false;
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
		Cursor cursor = context.getContentResolver().query(uri, new String[] {PhoneLookup.LOOKUP_KEY}, null, null, null);
		if(cursor != null) {
			if(cursor.moveToFirst()) {
				ret = true;
			}
			cursor.close();
		}
		return ret;
	}
}
